package cz.cvut.fit.crhonjar.mi.paa.thames;

import java.text.DecimalFormat;

/**
 * Represents item in Bag
 * 
 * @author Jarec
 * 
 */
public class Item {

	private final Integer originalIndex;
	private final Integer price;
	private Double pricePerWeightRatio;
	private Integer weight;

	/**
	 * Creates item with given price and weight
	 * 
	 * @param weight
	 * @param price
	 * @param originalIndex
	 */
	public Item(final Integer weight, final Integer price,
			final Integer originalIndex) {

		if (weight == null) {
			throw new IllegalArgumentException("weight is NULL!");
		}

		if (price == null) {
			throw new IllegalArgumentException("price is NULL!");
		}
		if (originalIndex == null) {
			throw new IllegalArgumentException("originalIndex is NULL!");
		}
		this.weight = weight;
		this.price = price;
		this.pricePerWeightRatio = null;
		this.originalIndex = originalIndex;
	}

	/**
	 * @return the originalIndex
	 */
	public Integer getOriginalIndex() {
		return this.originalIndex;
	}

	/**
	 * returns price of item
	 * 
	 * @return
	 */
	public Integer getPrice() {
		return this.price;
	}

	/**
	 * returns price per weight ratio
	 * 
	 * @return
	 */
	public Double getPricePerWeightRatio() {
		if (this.pricePerWeightRatio == null) {
			if (this.weight == 0) {
				this.pricePerWeightRatio = 0.;
			} else {
				this.pricePerWeightRatio = new Double(this.price) / this.weight;
			}
		}
		return this.pricePerWeightRatio;
	}

	/**
	 * returns weight of item
	 * 
	 * @return
	 */
	public Integer getWeight() {
		return this.weight;
	}

	@Override
	public int hashCode() {
		return this.originalIndex;
	}

	/**
	 * @param ignoredBits
	 */
	public void roundWeightBits(final int ignoredBits) {
		if ((this.weight % (1 << ignoredBits)) == 0) {
			this.weight = this.weight / (1 << ignoredBits);
		} else {
			this.weight = (this.weight + (1 << ignoredBits))
					/ (1 << ignoredBits);
		}

	}

	@Override
	public String toString() {
		final DecimalFormat df = new DecimalFormat("#.###");
		String str = "Item [weight=" + this.weight + ", price=" + this.price;
		if (this.pricePerWeightRatio != null) {
			str += ", pricePerWeight="
					+ df.format(this.pricePerWeightRatio.doubleValue());
		}
		return str + "]";
	}

}
